package com.example.excelzzk.controller;

import com.example.excelzzk.entity.Order;
import com.example.excelzzk.service.OrderService;
import com.example.excelzzk.util.JsonUtils;
import com.google.common.collect.Lists;
import com.wuwenze.poi.ExcelKit;
import com.wuwenze.poi.handler.ExcelReadHandler;
import com.wuwenze.poi.pojo.ExcelErrorField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ExcelController {

    @Autowired
    private OrderService orderService;

    // 生成导入模板（含3条示例数据）
//    @RequestMapping(value = "/downTemplate", method = RequestMethod.GET)
//    public void downTemplate(HttpServletResponse response) {
//        List<Order> userList = orderService.findAll();
//        ExcelKit.$Export(Order.class, response).downXlsx(userList, true);
//    }


    @RequestMapping(value = "/importUser", method = RequestMethod.POST)
    public ResponseEntity<?> importUser(@RequestParam MultipartFile file)
            throws IOException {
        long beginMillis = System.currentTimeMillis();

        List<Order> successList = Lists.newArrayList();
        List<Map<String, Object>> errorList = Lists.newArrayList();

        ExcelKit.$Import(Order.class)
                .readXlsx(file.getInputStream(), new ExcelReadHandler<Order>() {
                    @Override
                    public void onSuccess(int sheetIndex, int rowIndex, Order entity) {
                        successList.add(entity); // 单行读取成功，加入入库队列。
                    }

                    @Override
                    public void onError(int sheetIndex, int rowIndex,
                                        List<ExcelErrorField> errorFields) {
                        // 读取数据失败，记录了当前行所有失败的数据
                        Map errMap = new HashMap<String, Object>();
                        errMap.put("sheetIndex", sheetIndex);
                        errMap.put("rowIndex", rowIndex);
                        errMap.put("errorFields", errorFields);
                        errorList.add(errMap);
                    }
                });

        // TODO: 执行successList的入库操作。
        for (Order order : successList) {
            orderService.save(order);
        }
        Map<String, Object> succMap = new HashMap<>();
        succMap.put("data", successList);
        return ResponseEntity.ok(successList);
    }

    @RequestMapping(value = "/downXlsx", method = RequestMethod.GET)
    public void downXlsx(HttpServletResponse response) {
        long beginMillis = System.currentTimeMillis();
        List<Order> orderList = orderService.findAll();// 生成10w条测试数据
        ExcelKit.$Export(Order.class, response).downXlsx(orderList, false);
    }

    @GetMapping("/showList")
    public String showPage() {
        return "showList";
    }

    @GetMapping("/getAllList")
    @ResponseBody
    public String getAllList() {
        List<Order> list = orderService.findAll();
        Map<String, Object> resultMap = new HashMap();
        resultMap.put("code", 0);
        resultMap.put("msg", "");
        resultMap.put("count", list.size());
        resultMap.put("data", list);
        return JsonUtils.toJson(resultMap);
    }

}
